//
//  DoctorLIstResultViewController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/3/9.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
/// 搜索-医生列表
class DoctorLIstResultViewController: BaseViewController {
    
    private var doctorType: DoctorType
    
    private var departmentId: String = ""
    private var code: String = ""
    private var isPrescription: String = ""
    private var diagType: Int
    private var content: String = ""
    private var current: Int = 1
    /// 从眼科检查来
    private let fromMyopia: Bool
    private let recordId: String
    private var resultModels: [DoctorReserveModel] = []
    
    
    init(doctorType: DoctorType, recordId: String = "", fromMyopia: Bool = false) {
        self.doctorType = doctorType
        self.diagType = doctorType.rawValue
        self.recordId = recordId
        self.fromMyopia = fromMyopia
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.titleView = searchBar
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        searchBar.becomeFirstResponder()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        searchBar.resignFirstResponder()
    }
    
    private var viewModel: DoctorReserveViewModel? {
        didSet {
            tableView.reloadData()
        }
    }
    
    private lazy var searchBar: UISearchBar = {
        let searchBar = UISearchBar()
        searchBar.frame = CGRect(x: 0, y: 0, width: 100, height: 30)
        searchBar.barTintColor = .white
        searchBar.placeholder = "按疾病/医生名/科室搜索"
        searchBar.tintColor = .textDark
        searchBar.setBackgroundImage(UIImage(color: .white), for: .any, barMetrics: .default)
        searchBar.delegate = self
        return searchBar
    }()
    
    @IBOutlet private weak var topView: DoctorReserveTopView! {
        didSet {
            topView.delegate = self
            topView.configure(with: doctorType)
        }
    }
    
    private var alertView: DoctorReserveMenuView?
    
    @IBOutlet private var activityView: UIActivityIndicatorView!

    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.keyboardDismissMode = .onDrag
            tableView.backgroundColor = .background
            tableView.tableFooterView = UIView()
            tableView.register(DoctorReserveCell.nibForCell(),
                               forCellReuseIdentifier: DoctorReserveCell.reuseIdentifier())
            tableView.mj_header = refreshHeader(action: #selector(loadData))
            tableView.mj_footer = refreshFooter(action: #selector(loadMore))
        }
    }
    @objc func loadMore() {
        current = current + 1
        requestData()
    }
    
    func requestData() {
        activityView.startAnimating()
        DoctorReserveViewModel.getDoctorReserveList(type : 2,
            departmentId: departmentId,
                                                    diagType: diagType,
                                                    content: content,
                                                    current: current,
                                                    size: 10,
                                                    code: code,
                                                    isPrescription: isPrescription,
                                                    success: { models in
            self.activityView.stopAnimating()
            if self.current == 1 {
                self.resultModels = models
            } else {
                self.resultModels.append(contentsOf: models)
            }
            self.viewModel = DoctorReserveViewModel(models: self.resultModels)
            
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            
        }) { errorMsg in
            self.activityView.stopAnimating()
            HUDTool.showError(message: errorMsg)
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
        }
    }
    
   @objc func loadData() {
       current = 1
       requestData()
   }
}

extension DoctorLIstResultViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel?.numberOfRows ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: DoctorReserveCell.reuseIdentifier(),
                                                 for: indexPath) as! DoctorReserveCell
        cell.delegate = self
        if let vm = viewModel?.viewModel(of: indexPath) {
            cell.configure(with: vm, type: doctorType)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        guard let vm = viewModel?.viewModel(of: indexPath) else { return 0 }
        return vm.cellHeight(type: doctorType)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        guard let vm = viewModel?.viewModel(of: indexPath) else { return }
        
        switch doctorType {
        case .advisory:
            reserveAdvisory(vm, type: .advisory)
        case .cloud:
            reserveCloud(vm, type: .cloud)
        default:
            pushDoctorDetail(with: vm)
        }
    }
}

extension DoctorLIstResultViewController: DoctorReserveCellDelegate {
    func doctorReserveCell(_ cell: DoctorReserveCell, willReserveCloud type: DoctorType) {
        guard let indexPath = tableView.indexPath(for: cell),
            let vm = viewModel?.viewModel(of: indexPath) else { return }
        reserveCloud(vm, type: type)
    }
    
    func doctorReserveCell(_ cell: DoctorReserveCell, willReserveAdvisory type: DoctorType) {
        guard let indexPath = tableView.indexPath(for: cell),
            let vm = viewModel?.viewModel(of: indexPath) else { return }
        reserveAdvisory(vm, type: type)
    }
}

extension DoctorLIstResultViewController: UISearchBarDelegate {
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        content = searchBar.text!
        loadData()
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        content = searchBar.text!
        loadData()
    }
}

extension DoctorLIstResultViewController: DoctorReserveTopViewDelegate {
    func didClickedDoctorReserveTopView(type: DoctorReserveTopViewType, dismiss: Bool) {
        if dismiss {
            alertView?.dismiss()
        } else {
            alertView = UINib.loadViewFrom(DoctorReserveMenuView.self)
            alertView?.frame = CGRect(x: 0, y: topView.bottom, width: screenW, height: screenH - topView.bottom)
            alertView?.show(in: view, type: type)
            alertView?.clickedClosure = { [weak self] (code, name) in
                if let strongSelf = self {
                    switch type {
                    case .department:
                        strongSelf.departmentId = code
                    case .doctorType:
                        strongSelf.diagType = code.intValue
                    case .office:
                        strongSelf.code = code
                    case .prescription:
                        strongSelf.isPrescription = code
                    }
                    
                    strongSelf.tableView.mj_header?.beginRefreshing()
                   // strongSelf.loadData()
                    strongSelf.topView.setTitle(name, type: type)
                }
            }
            alertView?.cancelClosure = { [weak self] in
                self?.topView.reset(type)
            }
        }
    }
}

// MARK: - Helpers
extension DoctorLIstResultViewController {
    private func pushDoctorDetail(with vm: DoctorReserveRowViewModel) {
        let detailVc = DoctorDetailController(with: vm.doctorId)
        navigationController?.pushViewController(detailVc, animated: true)
    }
    
    private func reserveAdvisory(_ vm: DoctorReserveRowViewModel, type: DoctorType) {
        let model = DoctorDetail(id: vm.doctorId,
                                 deptId: vm.departmentId,
                                 docName: vm.doctorName,
                                 deptName: vm.department,
                                 hospitalName: vm.hospitalName,
                                 jobTitleName: vm.office,
                                 docGoodAtNames: vm.specialty,
                                 thumbnailUrl: vm.thumbnailUrl,
                                 score: vm.score.floatValue,
                                 fee: vm.fee,
                                 diagType: type.rawValue)
        let doctorDetail = DoctorDetailViewModel(model: model,
                                                 selectType: .advisory)
//        let newAdvisoryVc = NewAdvisoryController(with: doctorDetail, recordId: recordId, fromMyopia: fromMyopia)
//        navigationController?.pushViewController(newAdvisoryVc, animated: true)
        let adMedicalRecordsVC = AdMedicalRecordsController()
        adMedicalRecordsVC.doctorVm = doctorDetail
        adMedicalRecordsVC.recordId = recordId
        adMedicalRecordsVC.fromMyopia = fromMyopia
        navigationController?.pushViewController(adMedicalRecordsVC, animated: true)
    }
    
    private func reserveCloud(_ vm: DoctorReserveRowViewModel, type: DoctorType) {
        let model = DoctorDetail(id: vm.doctorId,
                                 deptId: vm.departmentId,
                                 docName: vm.doctorName,
                                 deptName: vm.department,
                                 hospitalName: vm.hospitalName,
                                 jobTitleName: vm.office,
                                 docGoodAtNames: vm.specialty,
                                 thumbnailUrl: vm.thumbnailUrl,
                                 score: vm.score.floatValue,
                                 fee: vm.fee,
                                 diagType: type.rawValue)
        let doctorDetail = DoctorDetailViewModel(model: model,
                                                 selectType: .cloud)
        let newCloudVc = NewCloudReserveController(with: doctorDetail)
        navigationController?.pushViewController(newCloudVc, animated: true)
    }
}
